import requests
import json
from bs4 import BeautifulSoup
import subprocess
import re
import tempfile
import os


class WjwExplain(object):

    def __init__(self, link):
        self.link = link
        self.json_explained_param = ""

    def get_initial_state_obj(self):
        # 假设response是包含HTML响应的字符串
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
        }
        if self.link.__contains__('/t/'):
            self.link = self.link.split('/t/')[0] + '/s/' + self.link.split('/t/')[1]
        response = requests.get(self.link, allow_redirects=False, headers=header, timeout=10)
        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(response.content, 'html.parser')
        script_tags = soup.find_all('script')
        json_str = ''
        for i in script_tags:
            t = i.text
            if i and t.startswith('window.__INITIAL_STATE__='):
                t = t.replace('window.__INITIAL_STATE__=', '')
                if t:
                    arr = t.split(';(function()')
                    json_str = arr[0]
        if not json_str:
            print('解析问卷失败，没有获取到题目内容')
        self.json_explained_param = json_str

    def convert_to_common_struct(self):
        # 原始数据字符串不能包含换行符“\n” 或者额外引号比如css样式style后的“，否则报错，需要提前去掉
        src_data = self.json_explained_param
        if not src_data:
            return ""
        src_data = src_data.replace('\n', '')
        src_data = re.sub(r'style=\".*?\"', '', src_data)
        js_file = './js_file/wjw/retrieve2invoke.js'
        p = subprocess.Popen(['node', js_file, src_data], stdout=subprocess.PIPE)
        res = p.stdout.read().decode().strip()
        if not res:
            return ""
        return json.loads(res)

    def convert_to_common_struct2(self):
        # 原始数据字符串不能包含换行符“\n” 或者额外引号比如css样式style后的“，否则报错，需要提前去掉
        src_data = self.json_explained_param
        if not src_data:
            return ""
        src_data = src_data.replace('\n', '')
        src_data = re.sub(r'style=\".*?\"', '', src_data)
        # 保存 src_data 到临时文件
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(src_data.encode())
        # 执行 Node.js 脚本，并从临时文件中读取数据
        js_file = './js_file/wjw/retrieve2invoke_v2.js'
        p = subprocess.Popen(['node', js_file, temp_file.name], stdout=subprocess.PIPE)
        res = p.stdout.read().decode().strip()
        # 删除临时文件
        temp_file.close()
        os.remove(temp_file.name)
        if not res:
            return ""
        return json.loads(res)

    def do_explain(self):
        self.get_initial_state_obj()
        return self.convert_to_common_struct2()
